package cn.ddcollection.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.jets3t.service.S3Service;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.security.AWSCredentials;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ddcollection.model.AccessKey;
import cn.ddcollection.model.DataCollector;
import cn.ddcollection.service.DataCollectorService;
import cn.ddcollection.service.SSSService;
import cn.ddcollection.utils.PropertiesOperatator;

/**
 * @author 作者 E-mail:
 * @date 创建时间：2016年4月6日 下午3:41:22
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
@Controller
@RequestMapping("/data")
public class DataController {

	@Resource(name = "sssService")
	private SSSService sssService;
	@Resource(name = "dataColloctorService")
	private DataCollectorService dataCollectorService;

	AWSCredentials awsCredentials = null;
	// 创建S3Service对象
	S3Service s3Service = null;
	// 声明bucket
	S3Bucket testBucket;

	@RequestMapping("todata")
	public String toData() {
		return "data/datacol";
	}

	@RequestMapping("addCollector")
	public String addCollector(@RequestParam("datacollectorname") String datacollectorname,
			@RequestParam("uploadfile") CommonsMultipartFile file, HttpServletRequest request) {
		List<AccessKey> accessKeys = PropertiesOperatator
				.getUserName(this.getClass().getClassLoader().getResource("").getPath() + "conf/userkey.properties");
		for (AccessKey accessKey : accessKeys) {
			awsCredentials = new AWSCredentials(accessKey.getUserkey().split(" ")[0],
					accessKey.getUserkey().split(" ")[1]);
			s3Service = new RestS3Service(awsCredentials);
			try {
				if (!file.isEmpty()) {
					String fileName = file.getOriginalFilename();
					String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);
					// 上传S3
					if (sssService.uploadObject(file, fileName, path, s3Service,
							"datacollector_" + accessKey.getUsername())) {
						// 存储数据库
						dataCollectorService
								.insertDataCollector(
										new DataCollector(
												fileName, "", datacollectorname, "https://s3.amazonaws.com/"
														+ "datacollector_" + accessKey.getUsername() + "/" + fileName,
												"", ""));
					} else {
						return "data/datacol";
					}
				} else {
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "data/datacol";
	}
}
